<?php

namespace wx;

use app\api\model\BaseModel;
use think\Cache;

class WxMessage
{
    private $app_id;
    private $app_secret;
    private $token_key = 'jsk_wx_access_token';
    private $file = 'jsk_wx_message1';
    private $token;

    public function __construct()
    {
        $this->token_key = BaseModel::accessTokenKey();
        $config = config('wx');
        $this->app_id = $config['app_id'];
        $this->app_secret = $config['secret'];
        if (!Cache::has($this->token_key)) {
            $this->getToken();
        }
        $this->token = Cache::get($this->token_key);
    }

    //获取token
    public function getToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
        $result = $this->https_request($url);
        if ($result) {
            $result = json_decode($result, true);
            Cache::set($this->token_key, $result['access_token'], 7195);//access_token每天只能获取200次，有效期是7200秒
            return $result['access_token'];
        }
        return false;
    }


    //发送模板消息
    public function send_template_message($data = '')
    {
        $token = Cache::get($this->token_key);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $token;
        $result = $this->https_request($url, $data);
        BaseModel::log($this->file, $result);
        if ($result) {
            $result = json_decode($result, true);
            if ($result['errcode'] == 0) {
                return true;
            }
        }
        return false;
    }


    public function https_request($url, $data = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if ($data) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            file_put_contents('wx_message_error', curl_error($curl) . "\r\n");
            return false;
        }
        curl_close($curl);
        BaseModel::log($this->file, $result);
        if (!$result) {
            file_put_contents('wx_message_error', '返回数据返回' . "\r\n");
            return false;
        }
        $res = json_decode($result, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            file_put_contents('wx_message_error', $res['errmsg'] . "\r\n");
            return false;
        }
        return $result;
    }

    //下单成功消息
    public function createOrderMessage($openid, $order)
    {
        $template = array(
            'touser' => $openid,
            'template_id' => 'O995ZKM1eSQWEj0KZunz0GYYr49_KXog1fLANVqQOtU',
            'data' => array(
                'character_string1' => array('value' => urlencode($order['no'])),  //订单编号
                'phrase2' => array('value' => urlencode('下单成功')),  //订单状态
                'time3' => array('value' => urlencode(date('Y-m-d H:i:s', $order['createtime']))), //创建时间
                'thing4' => array('value' => urlencode('请耐心等待接单，保持电话畅通~')),   //温馨提示
            )
        );
        $template = urldecode(json_encode($template));
        return $template;
    }

    //取消订单消息
    public function cancelOrderMessage($openid, $order, $cancel_reason = '用户取消', $mark = '用户取消')
    {
        $template = array(
            'touser' => $openid,
            'template_id' => 'FStnpTZMlcqgvAI20FoNL0qNI3C8AeRMQyzvyHZJcFI',
            'data' => array(
                'character_string1' => array('value' => urlencode($order['no'])),  //订单编号
                'time2' => array('value' => urlencode(date('Y-m-d H:i:s', $order['createtime']))),  //下单时间
                'thing3' => array('value' => urlencode($cancel_reason)),   //取消原因
                'thing4' => array('value' => urlencode($mark)),   //备注
            )
        );
        $template = urldecode(json_encode($template));
        return $template;
    }

    //接收订单消息
    public function takeOrderMessage($openid, $order, $rider)
    {
        $template = array(
            'touser' => $openid,
            'template_id' => 'cw0r-EXIiXaJmYQr4Cmoq_Un3FO48mfkJEmxWMncf24',
            'data' => array(
                'character_string1' => array('value' => urlencode($order['no'])),  //订单号
                'time6' => array('value' => urlencode(date('Y-m-d H:i:s', $order['take_time']))), //接单时间
                'thing13' => array('value' => urlencode($rider['real_name'])),  //回收员姓名
            )
        );
        $template = urldecode(json_encode($template));
        return $template;
    }

    /**
     * 家政订单消息
     * @param $openid 用户openid
     * @param $goods_title 服务项目名称
     * @param $order 订单信息
     * @return string

    订单编号
    {{character_string1.DATA}}

    服务项目
    {{thing4.DATA}}

    服务类型
    {{thing5.DATA}}

    预约时间
    {{time6.DATA}}

    温馨提示
    {{thing3.DATA}}
     */
    public function takeHomeOrderMessage($openid, $goods_title,$order=[])
    {
        $template = array(
            'touser' => $openid,
            'template_id' => '9mN2hGt3n5Yi7iw3oUfkA0S8Hgzt7Qu_USA2NMJk7cY',
            'data' => array(
                'thing5' => array('value'=>urlencode('家政接单')),
                'thing4' => array('value'=>urlencode($goods_title)),
                'character_string1' => array('value' => urlencode($order['no'])),  //订单号
                'thing3' => array('value'=>urlencode($order['role_name'].'已接单，请做好准备哦')),
                'time6' => array('value' => urlencode($order['reserve_time'])), //预约时间
            )
        );
        $template = urldecode(json_encode($template));
        return $template;
    }

}